<template>
  <div class="appointment-page">
    <h1 class="page-title">在线挂号</h1>

    <!-- 挂号表单 -->
    <el-card class="appointment-form">
      <el-form :model="form" label-width="100px">
        <el-form-item label="选择科室" required>
          <el-select v-model="form.department" placeholder="请选择科室" style="width: 100%">
            <el-option label="内科" value="内科"></el-option>
            <el-option label="外科" value="外科"></el-option>
            <el-option label="儿科" value="儿科"></el-option>
            <el-option label="妇产科" value="妇产科"></el-option>
            <el-option label="眼科" value="眼科"></el-option>
            <el-option label="耳鼻喉科" value="耳鼻喉科"></el-option>
            <el-option label="皮肤科" value="皮肤科"></el-option>
            <el-option label="中医科" value="中医科"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="选择医生" required>
          <el-select v-model="form.doctor" placeholder="请选择医生" style="width: 100%">
            <el-option v-for="doctor in doctors" :key="doctor.id" :label="doctor.name" :value="doctor.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="选择日期" required>
          <el-date-picker
            v-model="form.date"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
            :disabled-date="disabledDate">
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="searchDoctors" style="width: 100%">预约</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref } from 'vue'
import { SuccessFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { getUserInfo } from '@/api/user.js'
import request from '@/utils/request.js'

export default {
  name: 'Appointment',
  components: {
    SuccessFilled
  },
  setup() {
    const form = ref({
      department: '',
      doctor: '',
      date: ''
    })

    const showDoctorList = ref(false)
    const showConfirmDialog = ref(false)
    const showSuccessDialog = ref(false)
    const selectedTime = ref(null)
    const selectedDoctor = ref(null)
    const appointmentNumber = ref('20231115001')

    const doctors = ref([
      { id: 1, name: '张明华', title: '主任医师', department: '内科' },
      { id: 2, name: '王建国', title: '主任医师', department: '外科' },
      { id: 3, name: '李静', title: '副主任医师', department: '儿科' },
      { id: 4, name: '赵雪梅', title: '副主任医师', department: '妇产科' }
    ])

    const availableDoctors = ref([
      {
        id: 1,
        name: '张明华',
        title: '主任医师',
        department: '内科',
        hospital: '北京协和医院',
        avatar: 'https://randomuser.me/api/portraits/men/42.jpg',
        schedule: [
          { time: '09:00-09:30', booked: false },
          { time: '10:00-10:30', booked: true },
          { time: '14:00-14:30', booked: false },
          { time: '15:00-15:30', booked: false }
        ]
      },
      {
        id: 2,
        name: '王建国',
        title: '主任医师',
        department: '外科',
        hospital: '北京协和医院',
        avatar: 'https://randomuser.me/api/portraits/men/32.jpg',
        schedule: [
          { time: '09:30-10:00', booked: false },
          { time: '10:30-11:00', booked: false },
          { time: '14:30-15:00', booked: true }
        ]
      }
    ])

    const confirmForm = ref({
      doctor: '',
      department: '',
      time: '',
      patientName: '',
      phone: '',
      symptoms: ''
    })

    const disabledDate = (time) => {
      // 禁用今天之前的日期
      return time.getTime() < Date.now() - 8.64e7
    }

    const router = useRouter()

    const makeAppointment = async () => {
      if (!form.value.department || !form.value.doctor || !form.value.date) {
        ElMessage.error('请完整填写预约信息')
        return
      }

      try {
        const userInfo = getUserInfo()
        if (!userInfo) {
          ElMessage.error('请先登录')
          return
        }

        const selectedDoctor = doctors.value.find(d => d.id === form.value.doctor)
        const appointmentData = {
          userId: userInfo.userId,
          userName: userInfo.userName,
          reAge: userInfo.userAge,
          reSex: userInfo.userSex,
          deptName: form.value.department,
          doctorName: selectedDoctor.name,
          appointmentTime: form.value.date
        }

        const res = await request.post('/registration/add', appointmentData)
        if (res.code === 200) {
          ElMessage.success('预约成功')
          router.push('/records')
        } else {
          ElMessage.error(res.message || '预约失败')
        }
      } catch (error) {
        ElMessage.error('预约失败: ' + (error.message || '网络错误'))
      }
    }

    const searchDoctors = () => {
      if (!form.value.department || !form.value.date) {
        ElMessage.error('请选择科室和日期')
        return
      }
      makeAppointment()
    }

    const selectTime = (doctor, time) => {
      if (time.booked) return
      
      selectedTime.value = time
      selectedDoctor.value = doctor
      
      confirmForm.value = {
        doctor: `${doctor.name} ${doctor.title}`,
        department: doctor.department,
        time: `${formatDate(form.value.date)} ${time.time}`,
        patientName: '',
        phone: '',
        symptoms: ''
      }
      
      showConfirmDialog.value = true
    }

    const confirmAppointment = () => {
      if (!confirmForm.value.patientName || !confirmForm.value.phone) {
        ElMessage.error('请输入患者姓名和联系电话')
        return
      }
      
      // 模拟API调用
      setTimeout(() => {
        showConfirmDialog.value = false
        showSuccessDialog.value = true
        
        // 更新预约状态
        const doctor = availableDoctors.value.find(d => d.id === selectedDoctor.value.id)
        const timeSlot = doctor.schedule.find(t => t.time === selectedTime.value.time)
        timeSlot.booked = true
      }, 500)
    }

    const backToAppointment = () => {
      showSuccessDialog.value = false
      // 生成新的预约号
      appointmentNumber.value = '2023' + Math.floor(Math.random() * 10000)
    }

    const formatDate = (date) => {
      if (!date) return ''
      const d = new Date(date)
      return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日`
    }

    return {
      form,
      doctors,
      availableDoctors,
      confirmForm,
      showDoctorList,
      showConfirmDialog,
      showSuccessDialog,
      appointmentNumber,
      disabledDate,
      searchDoctors,
      selectTime,
      confirmAppointment,
      backToAppointment
    }
  }
}
</script>

<style scoped>
.appointment-page {
  max-width: 1200px;
  margin: 0 auto;
}

.page-title {
  font-size: 28px;
  margin-bottom: 20px;
  color: #42b983;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.appointment-form {
  margin-bottom: 30px;
}

.section-title {
  font-size: 20px;
  margin: 30px 0 15px;
  color: #42b983;
}

.doctor-list {
  margin-bottom: 30px;
}

.doctor-card {
  margin-bottom: 20px;
}

.doctor-info {
  display: flex;
  align-items: center;
}

.doctor-avatar {
  margin-right: 20px;
}

.doctor-details {
  flex: 1;
}

.doctor-name {
  font-size: 18px;
  margin: 0 0 5px;
  color: #333;
}

.doctor-title {
  color: #666;
  margin: 0 0 5px;
  font-size: 14px;
}

.doctor-hospital {
  color: #999;
  margin: 0 0 15px;
  font-size: 14px;
}

.doctor-schedule {
  margin-top: 10px;
}

.schedule-tag {
  margin-right: 10px;
  margin-bottom: 10px;
  cursor: pointer;
}

.success-content {
  text-align: center;
}

.success-icon {
  margin-bottom: 20px;
}

.success-content h3 {
  margin: 0 0 15px;
  font-size: 20px;
}

.success-content p {
  margin: 5px 0;
  color: #666;
}

@media (max-width: 768px) {
  .doctor-info {
    flex-direction: column;
    text-align: center;
  }
  
  .doctor-avatar {
    margin-right: 0;
    margin-bottom: 15px;
  }
}
</style>
